package team.kirohuji.controller;

import java.io.IOException;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import team.kirohuji.domain.user.User;
import team.kirohuji.repository.jpa.user.UserRepository;
import team.kirohuji.service.user.UserService;
import team.kirohuji.utils.JWTUtil;
import team.kirohuji.utils.ResponseBean;
import team.kirohuji.utils.ShiroUtils;

/**
 * 
 * 用来管理用户的登录和查看用户的登录信息
 * 
 * @author kirohuji
 * @version 0.1
 */
@Controller
public class LoginController {
	private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

	@Resource
	private UserService userService;

	@Autowired
	private UserRepository userRepository;

	/**
	 * 登录
	 * 
	 * @param account
	 *            用户
	 * @return {@link team.kirohuji.utils.ResponseBean}
	 * @throws IOException
	 *             可能会抛出了一个IO异常
	 */
	@ResponseBody
	@RequestMapping(value = "/sign/in", method = RequestMethod.POST)
	public ResponseBean loginBuPost(@RequestBody User account) throws IOException {
		try {
			String username = account.getUsername();
			String password = account.getPassword();
			Subject subject = ShiroUtils.getSubject();
			// 1. 执行登录
			// 把用户名和密码封装为UsernamePasswordToken对象
			UsernamePasswordToken token = new UsernamePasswordToken(username, password);
			logger.debug("执行登录");
			subject.login(token);
			if (subject.isAuthenticated()) {
				logger.debug("登录成功");
				User user = userService.queryByLoginName(username);
				logger.debug("生成jwt，返回客户端");
				return new ResponseBean(200, "Login success", JWTUtil.sign(username, user.getPassword()));
			} else {
				return new ResponseBean(200, "You are guest", null);
			}
		} catch (UnknownAccountException e) {
			return new ResponseBean(401, e.getMessage(), null);
		} catch (IncorrectCredentialsException e) {
			return new ResponseBean(401, e.getMessage(), null);
		} catch (LockedAccountException e) {
			return new ResponseBean(401, e.getMessage(), null);
		} catch (ExcessiveAttemptsException e) {
			return new ResponseBean(401, e.getMessage(), null);
		} catch (AuthenticationException e) {
			System.out.println(e.getMessage());
			return new ResponseBean(401, "账户验证失败", null);
		}
	}

	/**
	 * 登录
	 * 
	 * @param username
	 *            用户名
	 * @param password
	 *            密码
	 * @return {@link team.kirohuji.utils.ResponseBean}
	 * @throws IOException
	 *             可能会抛出了一个IO异常
	 */
	@ResponseBody
	@RequestMapping(value = "/sign/in", method = RequestMethod.GET)
	public ResponseBean login(String username, String password) throws IOException {
		try {
			Subject subject = ShiroUtils.getSubject();
			// 1. 执行登录
			// 把用户名和密码封装为UsernamePasswordToken对象
			UsernamePasswordToken token = new UsernamePasswordToken(username, password);
			subject.login(token);
			if (subject.isAuthenticated()) {
				User user = userService.queryByLoginName(username);
				return new ResponseBean(200, "Login success", JWTUtil.sign(username, user.getPassword()));
			} else {
				return new ResponseBean(200, "You are guest", null);
			}
		} catch (UnknownAccountException e) {
			return new ResponseBean(401, e.getMessage(), null);
		} catch (IncorrectCredentialsException e) {
			return new ResponseBean(401, e.getMessage(), null);
		} catch (LockedAccountException e) {
			return new ResponseBean(401, e.getMessage(), null);
		} catch (ExcessiveAttemptsException e) {
			return new ResponseBean(401, e.getMessage(), null);
		} catch (AuthenticationException e) {
			System.out.println(e.getMessage());
			return new ResponseBean(401, "账户验证失败", null);
		}
	}

	/**
	 * 退出
	 * 
	 * @param session
	 *            Http会话
	 * @return String 进行地址跳转
	 */
	@RequestMapping(value = "/sign/out", method = RequestMethod.GET)
	public String logout() {
		ShiroUtils.logout();
		return "redirect:login.html";
	}

	/**
	 * 注册
	 * 
	 * @return String 地址
	 */
	@ResponseBody
	@RequestMapping(value = "/sign/up/user", method = RequestMethod.POST)
	public User registerUser(@RequestBody User account) {
		String salt=ShiroUtils.salt();
		account.setSalt(salt);
		account.setAccountStatus(1);
		account.setPassword(ShiroUtils.MD5(account.getPassword(), salt));
		return userRepository.save(account);
	}
	/**
	 * 注册
	 * 
	 * @return String 地址
	 */
	@ResponseBody
	@RequestMapping(value = "/sign/up/info", method = RequestMethod.POST)
	public String registerInfo(@RequestBody User account) {
		return "page/register";
	}
}
